<template>
	<cl-dialog v-model="visible" title="修改学员信息" width="600px">
		<el-form ref="form" :model="formData" label-width="100px">
			<el-form-item label="姓名" prop="name">
				<el-input v-model="formData.name" />
			</el-form-item>
			<el-form-item label="电话" prop="phone">
				<el-input v-model="formData.phone" />
			</el-form-item>
			<el-form-item label="生日" prop="birthday">
				<el-date-picker
					v-model="formData.birthday"
					type="date"
					placeholder="选择日期"
					format="YYYY-MM-DD"
					value-format="YYYY-MM-DD"
				/>
			</el-form-item>
			<el-form-item label="项目" prop="project">
				<cl-select
					v-model="formData.project"
					placeholder="项目"
					:options="dict.get('Project')"
					:tree="true"
				/>
			</el-form-item>
			<el-form-item label="销售" prop="sales">
				<cl-select v-model="formData.sales" :options="salesList" />
			</el-form-item>
			<el-form-item label="跟进状态" prop="flowStatus">
				<cl-select v-model="formData.flowStatus" :options="dict.get('flowStatus')" />
			</el-form-item>
			<el-form-item label="入组" prop="inGroup">
				<cl-select v-model="formData.inGroup" :tree="true" :checkStrictly="true" :options="dict.get('inGroup')" />
			</el-form-item>
			<el-form-item prop="subway">
				<SelectSubway v-model="formData.subway" />
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="showAddReportDialog = true">添加报告</el-button>
				<el-button @click="handleViewReport">查看报告</el-button>
			</el-form-item>
		</el-form>
		<!-- 添加报告弹窗 -->
		<el-dialog v-model="showAddReportDialog" title="添加报告">
			<el-form :model="reportForm" label-width="100px">
				<el-form-item label="上传图片">
					<cl-upload v-model="reportForm.picUrl" />
				</el-form-item>
				<el-form-item label="备注">
					<el-input v-model="reportForm.remark" type="textarea" />
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="showAddReportDialog = false">取消</el-button>
				<el-button type="primary" @click="submitReport">确定</el-button>
			</template>
		</el-dialog>
		<el-dialog v-model="showViewReportDialog" title="查看报告">
			<div v-if="reportList.length > 0">
				<div v-for="report in reportList" :key="report.id" class="report-block">
					<el-image :src="report.picUrl" :preview-src-list="[report.picUrl]" />
					<p v-if="report.remark">{{ report.remark }}</p>
					<p v-else>暂无备注</p>
				</div>
			</div>
			<p v-else>暂无报告数据</p>
		</el-dialog>

		<template #footer>
			<el-button @click="handleCancel">取消</el-button>
			<el-button type="primary" @click="handleSave">确定</el-button>
		</template>
	</cl-dialog>
</template>

<script lang="ts" setup>
import { useCrud, useTable, useUpsert, useSearch } from "@cool-vue/crud";
import { ref, reactive, computed, watch } from 'vue';
import { useCool } from '/@/cool';
import { useDict } from '/$/dict';
import { ElMessage } from 'element-plus';
import SelectSubway from '../../student/components/select-subway.vue';

const { service } = useCool();
const { dict } = useDict();

const props = defineProps({
	modelValue: {
		type: Boolean,
		default: false
	},
	studentId: {
		type: [Number, String],
		default: 0
	}
});

const emit = defineEmits(['update:modelValue', 'success']);

const visible = computed({
	get: () => props.modelValue,
	set: val => emit('update:modelValue', val)
});

const salesList = ref([]);
const formData = reactive({
	id: 0,
	name: '',
	phone: '',
	birthday: '',
	project: '',
	sales: '',
	flowStatus: '',
	inGroup: '',
	subway: ''
});

// 控制添加报告弹窗的显示与隐藏
const showAddReportDialog = ref(false);
const showViewReportDialog = ref(false);

// 报告表单数据
const reportForm = reactive({
	picUrl: '',
	remark: '',
	studentId: props.studentId
});

// 初始化销售列表和学员信息
async function initData() {
	try {
		// 获取销售列表
		const salesRes = await service.base.sys.user.getSelectList();
		if (salesRes) {
			salesList.value = salesRes;
		}

		// 获取学员信息
		if (props.studentId) {
			const studentRes = await service.student.student.info({
				id: props.studentId
			});

			Object.assign(formData, {
				id: studentRes.id,
				name: studentRes.name,
				phone: studentRes.phone,
				birthday: studentRes.birthday,
				project: studentRes.project,
				sales: studentRes.sales,
				flowStatus: studentRes.flowStatus,
				inGroup: studentRes.inGroup
			});
			
			reportForm.studentId = props.studentId;
		}
	} catch (error) {
		console.error('初始化数据失败:', error);
	}
}

// 提交报告
const submitReport = async () => {
	if (!reportForm.picUrl) {
		ElMessage.warning('请上传图片');
		return;
	}

	try {
		await service.student.studentProfile.add({
			picUrl: reportForm.picUrl,
			studentId: reportForm.studentId,
			remark: reportForm.remark
		});
		ElMessage.success('报告添加成功');
		showAddReportDialog.value = false;
	} catch (error) {
		ElMessage.error('报告添加失败');
	}
};

// 保存
async function handleSave() {
	try {
		await service.student.student.update(formData);
		ElMessage.success('保存成功');
		visible.value = false;
		emit('success');
	} catch (error) {
		ElMessage.error('保存失败');
	}
}

const handleCancel = () => {
	visible.value = false;
};

const reportList = ref([]);
// 获取报告列表
const getReportList = async () => {
	try {
		const params = {
			order: "createTime",
			page: 1,
			size: 20,
			sort: "desc",
			studentId: props.studentId
		};
		const res = await service.student.studentProfile.page(params);
		console.log('获取的报告列表:', res); // 添加日志输出，查看返回的数据结构和内容
		if (res && res.list) {
			reportList.value = res.list;
			console.log('获取报告列表成功:', reportList.value); // 添加日志输出
		} else {
			console.log('获取的报告列表为空:', res);
		}
	} catch (error) {
		console.error('获取报告列表失败:', error);
		ElMessage.error('获取报告列表失败');
	}
};

// 修改查看报告处理函数
const handleViewReport = async () => {
	reportList.value = []; 
	await getReportList();
	showViewReportDialog.value = true;
};

// 监听弹窗显示状态，显示时初始化数据
watch(
	() => visible.value,
	val => {
		if (val && props.studentId) {
			initData();
		}
	}
);

// 监听学员ID变化
watch(
	() => props.studentId,
	val => {
		if (visible.value && val) {
			initData();
		}
	}
);

// 监听添加报告弹窗显示状态
watch(showAddReportDialog, (newVal) => {
    if (!newVal) {
        // 当弹窗关闭时，重置图片和备注
        reportForm.picUrl = '';
        reportForm.remark = '';
    }
});

defineExpose({
	formData
});
</script>
<style scoped>
.report-block {
	border: 1px solid #eee;
	padding: 10px;
	margin-bottom: 10px;
	border-radius: 4px;
}
</style>